package com.example.demo.controller;

import com.example.demo.service.SysUserService;
import com.example.demo.dao.Creation;
import com.example.demo.domain.SysUser;
import com.example.demo.controller.BaseController;
import com.example.demo.datatable.PageParameter;
import com.example.demo.datatable.PageResult;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Controller
@RequestMapping("/sysUser")
public class SysUserController extends BaseController{
    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/addView")
    public String addView(){
        return "buss/sysUser/add";
    }

    @GetMapping("/listView")
    public String listView(){
        return "buss/sysUser/list";
    }

    @GetMapping("/updateView")
    public String updateView(String id, ModelMap modelMap){
        modelMap.addAttribute("id", id);
        return "buss/sysUser/add";
    };

    @GetMapping
    @ResponseBody
    public PageResult list(PageParameter pageParameter, HttpServletRequest request){
        PageHelper.offsetPage(pageParameter.getOffset(), pageParameter.getLimit());
        if(!StringUtils.isEmpty(pageParameter.getSort()))
        PageHelper.orderBy(pageParameter.getSort() + " " + pageParameter.getSort());

        Page page = (Page)sysUserService.grid(generateCreationsFormRequest(request));
        return new PageResult(page.getTotal(), page.getResult());
    }

    @ResponseBody
    @PostMapping
    public ResponseEntity save(@RequestBody SysUser sysUser){
        if(StringUtils.isEmpty(sysUser.getId())){
            sysUserService.insert(sysUser);
        }else{
            sysUserService.update(sysUser);
        }
        return ResponseEntity.ok("success");
    }

    @GetMapping("/{id}")
    @ResponseBody
    public ResponseEntity get(@PathVariable String id){
        SysUser entity = sysUserService.get(id);
        return ResponseEntity.ok(entity);
    }

    @DeleteMapping("/{id}")
    @ResponseBody
    public ResponseEntity delete(@PathVariable String id){
        sysUserService.delete(id);
        return ResponseEntity.ok("success");
    }

    @DeleteMapping
    @ResponseBody
    public ResponseEntity batchDelete(String ids){
        Arrays.asList(ids.split(",")).forEach(sysUserService::delete);
        return ResponseEntity.ok("success");
    }
}
